// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const wxContext = cloud.getWXContext()
    
    // 初始化用户 - 创建管理员账户
    const adminResult = await initAdminUser(wxContext.OPENID)
    
    // 初始化检查项
    const checkItemsResult = await initCheckItems()
    
    // 初始化示例宿舍
    const dormsResult = await initDorms()
    
    return {
      success: true,
      message: '数据库初始化成功',
      details: {
        admin: adminResult,
        checkItems: checkItemsResult,
        dorms: dormsResult
      }
    }
  } catch (err) {
    console.error('初始化数据库失败', err)
    return {
      success: false,
      message: '初始化数据库失败',
      error: err
    }
  }
}

// 初始化管理员用户
async function initAdminUser(openid) {
  try {
    // 检查用户是否已存在
    const userCheck = await db.collection('users').where({
      openid: openid
    }).get()
    
    if (userCheck.data.length > 0) {
      // 用户已存在，更新为管理员
      await db.collection('users').doc(userCheck.data[0]._id).update({
        data: {
          role: '管理员',
          updateTime: new Date()
        }
      })
      
      return {
        success: true,
        message: '已将现有用户设置为管理员',
        userId: userCheck.data[0]._id
      }
    }
    
    // 创建管理员用户
    const adminUser = {
      openid: openid,
      name: '系统管理员',
      avatar: '',
      role: '管理员',
      createTime: new Date()
    }
    
    const result = await db.collection('users').add({
      data: adminUser
    })
    
    return {
      success: true,
      message: '管理员用户创建成功',
      userId: result._id
    }
  } catch (error) {
    console.error('初始化管理员失败', error)
    return {
      success: false,
      message: '初始化管理员失败',
      error: error
    }
  }
}

// 初始化检查项
async function initCheckItems() {
  try {
    // 定义默认检查项
    const defaultCheckItems = [
      {
        name: "地面清洁",
        description: "地面无垃圾、无明显灰尘",
        maxScore: 30,
        weight: 0.3,
        category: "环境卫生",
        standard: "地面整洁，无垃圾，无明显灰尘，拖把摆放整齐",
        isRequired: true,
        order: 1
      },
      {
        name: "物品摆放",
        description: "个人物品摆放整齐有序",
        maxScore: 25,
        weight: 0.25,
        category: "物品摆放",
        standard: "床铺整洁，物品摆放有序，书籍整齐",
        isRequired: true,
        order: 2
      },
      {
        name: "垃圾分类",
        description: "垃圾分类正确，及时清理",
        maxScore: 20,
        weight: 0.2,
        category: "环境卫生",
        standard: "垃圾桶内垃圾分类正确，及时清理，不超过2/3容量",
        isRequired: true,
        order: 3
      },
      {
        name: "卫生间整洁",
        description: "卫生间无异味，设施清洁",
        maxScore: 15,
        weight: 0.15,
        category: "环境卫生",
        standard: "卫生间无异味，地面干燥，洗漱用品摆放整齐",
        isRequired: true,
        order: 4
      },
      {
        name: "安全隐患",
        description: "无违规电器，无安全隐患",
        maxScore: 10,
        weight: 0.1,
        category: "安全",
        standard: "无违规电器，线路整齐，无消防隐患",
        isRequired: true,
        order: 5
      }
    ]
    
    // 使用 manageCheckItems 云函数批量创建
    const result = await cloud.callFunction({
      name: 'manageCheckItems',
      data: {
        action: 'batchCreate',
        data: {
          items: defaultCheckItems
        }
      }
    })
    
    return result.result
  } catch (error) {
    console.error('初始化检查项失败', error)
    return {
      success: false,
      message: '初始化检查项失败',
      error: error
    }
  }
}

// 初始化示例宿舍
async function initDorms() {
  try {
    // 定义示例宿舍
    const sampleDorms = [
      { building: '1', roomNo: '101', currentScore: 85, medals: [] },
      { building: '1', roomNo: '102', currentScore: 92, medals: ['优秀宿舍'] },
      { building: '1', roomNo: '201', currentScore: 75, medals: [] },
      { building: '1', roomNo: '202', currentScore: 63, medals: [] },
      { building: '2', roomNo: '101', currentScore: 95, medals: ['优秀宿舍'] },
      { building: '2', roomNo: '102', currentScore: 55, medals: [] }, // 不合格宿舍，分数低于60，没有勋章
      { building: '2', roomNo: '201', currentScore: 78, medals: [] },
      { building: '2', roomNo: '202', currentScore: 88, medals: [] },
      { building: '3', roomNo: '101', currentScore: 91, medals: ['优秀宿舍'] },
      { building: '3', roomNo: '102', currentScore: 78, medals: [] }
    ];
    
    // 处理每个宿舍的数据，确保分数和勋章一致
    const processedDorms = sampleDorms.map(dorm => {
      // 根据分数确定正确的勋章
      let medals = [];
      if (dorm.currentScore >= 90) {
        medals = ['优秀宿舍'];
      }
      
      return {
        ...dorm,
        medals: medals,
        createTime: new Date(),
        updateTime: new Date(),
        scoreHistory: [{
          date: new Date(),
          score: dorm.currentScore,
          checkerId: 'system',
          checkerName: '系统初始化'
        }]
      };
    });
    
    // 使用 manageDorms 云函数批量创建
    const result = await cloud.callFunction({
      name: 'manageDorms',
      data: {
        action: 'batchCreate',
        data: {
          dorms: processedDorms
        }
      }
    });
    
    return result.result;
  } catch (error) {
    console.error('初始化宿舍失败', error);
    return {
      success: false,
      message: '初始化宿舍失败',
      error: error
    };
  }
}